#-*- coding:utf-8 -*-

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.db import connection, transaction
from django.contrib.auth.decorators import login_required
from update.tools.w_git import Git_version
from update.tools.w_update import server_cu
from update.tools.w_deployment import deployment_zcell
from update.models import z_ioip
from conf import config
from tools.w_decorator import Mysql
from django.contrib.auth.decorators import login_required

import json
import configparser
import pymysql
import traceback
import time
import re
import threading

mysqlcon = Mysql()

@csrf_exempt
@login_required(login_url='/login')
def zcellup(request):
    global zcell_up_list
    update_sql = "SELECT yic.companyId, yic.companyName, ccz.node, ccz.address FROM y_info_company AS yic, c_company_zcell_config AS ccz WHERE yic.companyId = ccz.companyId AND ccz.enabled = 1 AND yic.isUsing = 1 AND yic.isDelete = 0 AND ccz.isDelete = 0 ORDER BY yic.companyId"
    zcell_all_sql = "select * from z_ioip"
    mycursor = connection.cursor()
    mycursor.execute(zcell_all_sql)
    up_data = mysqlcon.getAll(update_sql)
    zcell_data = mycursor.fetchall()
    zcell_up_list = []
    zid = 1
    for i in up_data:
        zcell_up_json = {}
        try:
            try:
                zcell_name = [n[1] for n in zcell_data if i[3] in n].pop()
            except:
                zcell_name = ""
            zcell_up_json["id"] = zid
            zcell_up_json["companyid"] = i[0]
            zcell_up_json["companyname"] = i[1]
            zcell_up_json["zcellname"] = zcell_name
            zcell_up_json["nodename"] = i[2]
            zcell_up_json["zcellip"] = i[3]
            zid += 1
        except:
            traceback.print_exc()
        zcell_up_list.append(zcell_up_json)
    print('zcellup',zcell_up_list)
    mycursor.close()
    return render(request, 'update/zcell-update.html', {"zcell_up": json.dumps(zcell_up_list)})

@csrf_exempt
@login_required(login_url='/login')
def zcellde(request):
    deployment_sql = "SELECT address, count(1), count(distinct companyId) FROM c_company_zcell_config WHERE isDelete = 0 AND enabled = 1 GROUP BY address ORDER BY count(1) desc"
    company_sql = "SELECT yic.companyName, ccz.node, ccz.address FROM c_company_zcell_config AS ccz, y_info_company AS yic WHERE ccz.isDelete = 0 AND ccz.enabled = 1 AND yic.isUsing = 1 AND yic.isDelete = 0 AND yic.companyId = ccz.companyId "
    zcell_all_sql = "select * from z_ioip"
    mycursor = connection.cursor()
    mycursor.execute(zcell_all_sql)
    deployment_data = mysqlcon.getAll(deployment_sql)
    zcell_data = mycursor.fetchall()
    # cursor.execute(company_sql)
    deployment_company = mysqlcon.getAll(company_sql)
    zcell_de_list = []
    company_json = {}
    zid = 1
    for i in deployment_data:
        zcell_de_json = {}
        try:
            zcell_name = [n[1] for n in zcell_data if i[0] in n].pop()
            zcell_de_json["id"] = zid
            zcell_de_json["zcellname"] = zcell_name
            zcell_de_json["nodenumber"] = i[1]
            zcell_de_json["companynumber"] = i[2]
            zcell_de_json["zcellip"] = i[0]
            zid += 1
        except:
            traceback.print_exc()
        zcell_de_list.append(zcell_de_json)

    for m in deployment_company:
        company_one_list = []
        company_one_json = {}
        add_status = 0
        zcell_name = [n[1] for n in zcell_data if m[2] in n].pop()
        try:
            lists = company_json[zcell_name]
            for y in lists:
                if y["companyname"] == m[0]:
                    y["module"] = y["module"] + ',' + m[1]
                    add_status += 1
                    break
            if add_status == 0:
                company_one_json["companyname"] = m[0]
                company_one_json["module"] = m[1]
                lists.append(company_one_json)
        except:
            company_one_json["companyname"] = m[0]
            company_one_json["module"] = m[1]
            company_one_list.append(company_one_json)
            company_json[zcell_name] = company_one_list
    print('zcellde',company_json)
    print('zcellde',zcell_de_list)
    mycursor.close()
    return render(request, 'update/zcell-deployment.html', {"zcell_de": json.dumps(zcell_de_list), "company_de": json.dumps(company_json)})

@login_required(login_url='/login')
def zcellgit(request):
    git_module = Git_version()
    git_list = git_module.git_show()
    return render(request, 'update/zcell-git.html', { "gitdata":json.dumps(git_list)})

@login_required(login_url='/login')
def zcellde_add(request,v1, v2):
    git_module = Git_version()
    git_list = git_module.git_version()
    print('zcellde_add',git_list)
    return render(request, 'update/add_deployment.html', {"zcellname":json.dumps(v1), "zcellip":json.dumps(v2), "gitmodule":json.dumps(git_list)})

@login_required(login_url='/login')
def zcellgit_add(request, v1):
    return render(request, 'update/add_git.html',{"module":json.dumps(v1)})

@csrf_exempt
def updateselect(request):
    if request.is_ajax():
        if request.method == 'POST':
            r_data = {"status":1}
            try:
                companyname = eval(json.dumps(request.POST))['companyname']
                new_zcell_up_list = []
                if companyname == "":
                    new_zcell_up_list = zcell_up_list
                else:
                    pattern = re.compile(companyname)
                    for i in zcell_up_list:
                        results = pattern.findall(i['companyname'])
                        if results != []:
                            new_zcell_up_list.append(i)
                r_data["zcell_new_up"] = new_zcell_up_list
                r_data["status"] = 0
            except BaseException as b:
                _log_err = "updateselect函数异常 --》" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps(r_data))


@csrf_exempt
def updaterequest(request):
    if request.is_ajax():
        if request.method == "POST":
            r_data = {"status":1}
            try:
                zcell_name_sql = "select zcell from z_ioip"
                mycursor = connection.cursor()
                mycursor.execute(zcell_name_sql)
                zcell_name = mycursor.fetchall()
                mycursor.close()
                if request.is_ajax():
                    if request.method == 'POST':
                        up_data = eval(json.dumps(request.POST))
                        status = int(up_data['status'])
                        if status == 1:
                            up_list = []
                            for i in  zcell_name:
                                up_list.append(i[0])
                            print('全部更新，更新列表：',up_list)
                            update_send = server_cu(up_list, status)
                            update_send.start()
                            update_send.join()
                            r_data["status"] = update_send.return_code
                            # t = threading.Thread(target=update_send.main_body, args=(up_list, status,))
                            # t.start()
                            # t.join()
                        else:
                            data = up_data["data"].replace('\'', '"')
                            up_list = json.loads(data)
                            #list为批量更新
                            if type(up_list) == type([]):
                                send_up_list = []
                                for i in up_list:
                                    up_json = {}
                                    module_list = []
                                    old = 0
                                    #合并同个zcell下的不同模块
                                    for n in send_up_list:
                                        if n["id"] == i["zcellname"]:
                                            n["module"].append(i["nodename"])
                                            n["number"] = len(n["module"])
                                            old = 1
                                            break

                                    if old == 0:
                                        up_json["id"] = i["zcellname"]
                                        module_list.append(i["nodename"])
                                        up_json["module"] = module_list
                                        up_json["number"] = len(module_list)
                                        up_json["ip"] = i["zcellip"]
                                        send_up_list.append(up_json)
                                print('批量更新，更新列表：',send_up_list)
                                # t = threading.Thread(target=update_send.main_body, args=(send_up_list, status,))
                                # t.start()
                                # t.join()
                                update_send = server_cu(send_up_list, status)
                                update_send.start()
                                update_send.join()
                                r_data["status"] = update_send.return_code
                                # update_send.main_body(send_up_list, status)
                            else:
                                send_up_list = []
                                up_json = {}
                                module_list = []
                                up_json["id"] = up_list["zcellname"]
                                module_list.append(up_list["nodename"])
                                up_json["module"] = module_list
                                up_json["number"] = len(module_list)
                                up_json["ip"] = up_list["zcellip"]
                                send_up_list.append(up_json)
                                print('单一更新，更新列表：',send_up_list)
                                # t = threading.Thread(target=update_send.main_body, args=(send_up_list, status,))
                                # t.start()
                                # t.join()
                                update_send = server_cu(send_up_list, status)
                                update_send.start()
                                update_send.join()
                                r_data["status"] = update_send.return_code
            except BaseException as b:
                _log_err = "updaterequest 函数异常 --》" + str(b)
                print(_log_err)
            finally:
                print(r_data)
                return HttpResponse(json.dumps(r_data))

@csrf_exempt
def deploymentrequest(request):
    r_data = {"status":1}
    try:
        config_file = r'conf\config.ini'
        config = configparser.ConfigParser()
        config.read(config_file, encoding="utf-8")
        deployment_list = []
        if request.is_ajax():
            if request.method == 'POST':
                deployment_data = eval(json.dumps(request.POST))
                data = deployment_data["data"].replace('\'','"')
                deployment_json = json.loads(data)
                if deployment_json["configchoose"] == 'on':
                    if deployment_json["modulename"][0:2] == 'AS':
                        for i in config.options('defaultconfig'):
                            rules = config.get('defaultconfig',i)
                            rule_list = rules.split('|')
                            if rule_list[0] == 'Startup.ini':
                                rule_list[2] = rule_list[2] + '=' + deployment_json["filename"] +'.exe'
                            else:
                                rule_list[2] = rule_list[2] + '=' + deployment_json["filename"]
                            deployment_json["configuration"].append(rule_list)
                    else:
                        for i in config.options('defaultconfigv'):
                            rules = config.get('defaultconfigv',i)
                            rule_list = rules.split('|')
                            if rule_list[0] == 'Startup.ini':
                                rule_list[2] = rule_list[2] + '=' + deployment_json["filename"] +'.exe'
                            else:
                                rule_list[2] = rule_list[2] + '=' + deployment_json["filename"]
                            deployment_json["configuration"].append(rule_list)
                print('deploymentrequest',deployment_json)
                deployment_list.append(deployment_json)
                deployment_send = deployment_zcell(deployment_list)
                deployment_send.start()
                deployment_send.join()
                r_data["status"] = deployment_send.return_code
    except BaseException as b:
        _log_err = "deploymentrequest函数 --》" + str(b)
        print(_log_err)
    finally:
        return HttpResponse(json.dumps(r_data))

@csrf_exempt

def gitrequest(request):
    if request.is_ajax():
        if request.method == 'POST':
            git_data = eval(json.dumps(request.POST))
            data = git_data["data"].replace('\'', '"')
            git_json = json.loads(data)
            print('gitrequest',git_json)
            return HttpResponse()
